package main

import (
	"encoding/json"
	"fronter/svrConnectMgr"
	mgr "fronter/svrConnectMgr"
	"time"

	"github.com/sirupsen/logrus"
)

func add(req mgr.AddTestReq, res *mgr.AddTestRes) {
	res.Res = req.Numa + req.Numb
}

func login(req mgr.ProtoUserLoginReq, res *mgr.ProtoUserLoginRes) {
	logrus.Infoln("login res, account:", req.Account, ", pwd:", req.Pwd)
	var resMap interface{}
	if svrConnectMgr.CallWithRetry("LoginGw", "/login", req, &resMap, time.Second*1, 3) != nil {
		logrus.Errorln("rpc logingw failed!")
		res.Rescode = 501
		return
	}
	//登录成功后需要保存此用户所在的网关地址
	realRes := resMap.(map[string]interface{})
	res.Rescode = int(realRes["rescode"].(float64))
	res.Token = realRes["token"].(string)
	res.Userid = int(realRes["userid"].(float64))
	logrus.Infoln("rpc success! resMap:", resMap)

}

func register(req mgr.ProtoUserRegReq, res *mgr.ProtoUserRegRes){
	var resMap interface{}
	if svrConnectMgr.CallWithRetry("LoginGw", "/register", req, &resMap, time.Second*1, 3) != nil {
		logrus.Errorln("rpc logingw failed!")
		res.Rescode = 501
		return
	}
	realRes := resMap.(map[string]interface{})
	res.Rescode = int(realRes["rescode"].(float64))
	logrus.Infoln("rpc success! resMap:", resMap)
}

func callback(proto_name string, data []byte) (string, []byte) {
	logrus.Infoln("name:", proto_name)
	switch proto_name {
	case "msgproto.addTestReq":
		var req mgr.AddTestReq
		var res mgr.AddTestRes
		json.Unmarshal(data, &req)
		add(req, &res)
		res_str, _ := json.Marshal(res)
		logrus.Infoln(res)
		return "msgproto.addTestRes", res_str
	case "msgproto.echoReq":
		var rsp string
		//svrConnectMgr.CallWithRetry("LoginGw", "/echo", data, rsp, time.Second*1, 3)
		return "msgproto.echoRes", []byte(rsp)
	case "msgproto.userLoginReq":
		var req mgr.ProtoUserLoginReq
		var res mgr.ProtoUserLoginRes
		json.Unmarshal(data, &req)
		login(req, &res)
		res_str, _ := json.Marshal(res)
		return "msgproto.userLoginRes", res_str
	case "msgproto.userRegisterReq":
		var req mgr.ProtoUserRegReq
		var res mgr.ProtoUserRegRes
		json.Unmarshal(data, &req)
		register(req, &res)
		res_str, _ := json.Marshal(res)
		return "msgproto.userRegisterRes", res_str
	}
	}
	
	return "null", []byte("{}")
}
func main() {
	var svr mgr.Server
	mgr.HandleCallback = callback
	//注册服务

	svr.Listen(8112)
}
